<template>
  <div class="processing-manage">
    <h1>📋 处理记录管理</h1>

    <el-tabs v-model="activeTab" v-loading="loading">
      <!-- 面试处理记录 -->
      <el-tab-pane label="面试处理记录" name="processing">
        <div class="tab-header">
          <el-button type="primary" @click="showAddProcessingDialog">
            <el-icon><Plus /></el-icon> 添加处理记录
          </el-button>
        </div>

        <el-empty v-if="processings.length === 0" description="暂无处理记录" />
        
        <el-table v-else :data="processings" stripe border>
          <el-table-column prop="record_id" label="记录ID" width="100" />
          <el-table-column prop="user_id" label="用户ID" width="100" />
          <el-table-column prop="company_name" label="公司名称" min-width="150" />
          <el-table-column prop="position_name" label="岗位名称" min-width="150" />
          <el-table-column label="处理状态" width="120">
            <template #default="{ row }">
              <el-tag :type="getProcessStatusType(row.process_status)">
                {{ getProcessStatusText(row.process_status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="处理时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.process_time) || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="reject_reason" label="打回原因" min-width="200" show-overflow-tooltip />
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="{ row }">
              <el-button type="warning" size="small" @click="editProcessing(row)">
                编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-if="processingPagination.pages > 1"
          class="pagination"
          :current-page="processingPagination.current"
          :page-size="processingPagination.pageSize"
          :total="processingPagination.total"
          layout="prev, pager, next, total"
          @current-change="handleProcessingPageChange"
        />
      </el-tab-pane>

      <!-- 面试结果 -->
      <el-tab-pane label="面试结果" name="result">
        <el-empty v-if="results.length === 0" description="暂无面试结果" />
        
        <el-table v-else :data="results" stripe border>
          <el-table-column prop="record_id" label="记录编号" width="100" />
          <el-table-column prop="user_id" label="用户ID" width="100" />
          <el-table-column prop="company_name" label="企业名称" min-width="150" />
          <el-table-column prop="position_name" label="岗位名称" min-width="150" />
          <el-table-column label="处理状态" width="120">
            <template #default="{ row }">
              <el-tag :type="getProcessStatusType(row.process_status)">
                {{ getProcessStatusText(row.process_status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.created_at) }}
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-if="resultPagination.pages > 1"
          class="pagination"
          :current-page="resultPagination.current"
          :page-size="resultPagination.pageSize"
          :total="resultPagination.total"
          layout="prev, pager, next, total"
          @current-change="handleResultPageChange"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- 添加/编辑处理记录对话框 -->
    <el-dialog
      v-model="processingDialogVisible"
      :title="processingForm.record_id ? '编辑面试处理记录' : '添加面试处理记录'"
      width="600px"
    >
      <el-form :model="processingForm" label-width="100px">
        <el-form-item label="用户ID">
          <el-input-number v-model="processingForm.user_id" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="公司名称">
          <el-input v-model="processingForm.company_name" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="岗位名称">
          <el-input v-model="processingForm.position_name" placeholder="请输入岗位名称" />
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="processingForm.process_status" placeholder="请选择处理状态">
            <el-option label="待处理" :value="1" />
            <el-option label="已通过" :value="2" />
            <el-option label="已打回" :value="3" />
            <el-option label="已过期" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="打回原因" v-if="processingForm.process_status === 3">
          <el-input
            v-model="processingForm.reject_reason"
            type="textarea"
            :rows="3"
            placeholder="请输入打回原因"
          />
        </el-form-item>
        <el-form-item label="处理时间">
          <el-date-picker
            v-model="processingForm.process_time"
            type="datetime"
            placeholder="选择处理时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="processingDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProcessing">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import instance from '@/utils/request'

const activeTab = ref('processing')
const loading = ref(false)

// 处理记录
const processings = ref([])
const processingPagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  pages: 0
})

// 面试结果
const results = ref([])
const resultPagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  pages: 0
})

// 对话框
const processingDialogVisible = ref(false)
const processingForm = ref({
  record_id: null,
  user_id: 1,
  company_name: '',
  position_name: '',
  process_status: 1,
  reject_reason: '',
  process_time: ''
})

// 加载处理记录（所有用户）
const loadProcessings = async (page = 1) => {
  loading.value = true
  try {
    const res = await instance.request({
      method: 'GET',
      url: '/resume-processing',
      params: { page, pageSize: 10 }
    })

    if (res && res.code === 200) {
      processings.value = res.data || []
      if (res.pagination) {
        processingPagination.value = res.pagination
      }
    } else {
      processings.value = []
      ElMessage.error(res?.message || '获取处理记录失败')
    }
  } catch (e) {
    console.error('获取处理记录失败:', e)
    ElMessage.error('获取处理记录失败')
    processings.value = []
  } finally {
    loading.value = false
  }
}

// 加载面试结果（所有用户）
const loadResults = async (page = 1) => {
  loading.value = true
  try {
    const res = await instance.request({
      method: 'GET',
      url: '/interview-result',
      params: { page, pageSize: 10 }
    })

    if (res && res.code === 200) {
      results.value = res.data || []
      if (res.pagination) {
        resultPagination.value = res.pagination
      }
    } else {
      results.value = []
      ElMessage.error(res?.message || '获取面试结果失败')
    }
  } catch (e) {
    console.error('获取面试结果失败:', e)
    ElMessage.error('获取面试结果失败')
    results.value = []
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleProcessingPageChange = (page) => {
  processingPagination.value.current = page
  loadProcessings(page)
}

const handleResultPageChange = (page) => {
  resultPagination.value.current = page
  loadResults(page)
}

// 显示添加对话框
const showAddProcessingDialog = () => {
  processingForm.value = {
    record_id: null,
    user_id: 1,
    company_name: '',
    position_name: '',
    process_status: 1,
    reject_reason: '',
    process_time: ''
  }
  processingDialogVisible.value = true
}

// 编辑处理记录
const editProcessing = (record) => {
  processingForm.value = {
    ...record,
    process_time: record.process_time || ''
  }
  processingDialogVisible.value = true
}

// 保存处理记录
const saveProcessing = async () => {
  if (!processingForm.value.company_name || !processingForm.value.position_name) {
    ElMessage.warning('请填写公司名称和岗位名称')
    return
  }

  try {
    const url = processingForm.value.record_id
      ? `http://localhost:7001/api/resume-processing/${processingForm.value.record_id}`
      : 'http://localhost:7001/api/resume-processing'
    
    const method = processingForm.value.record_id ? 'PUT' : 'POST'
    
    const res = await fetch(url, {
      method,
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(processingForm.value)
    })
    if (!res.ok) {
      throw new Error(`HTTP error! status: ${res.status}`)
    }
    
    const json = await res.json()
    if (json && (json.code === 200 || json.code === 201)) {
      ElMessage.success(processingForm.value.record_id ? '更新成功' : '添加成功')
      processingDialogVisible.value = false
      await loadProcessings(processingPagination.value.current)
    } else {
      ElMessage.error(json.message || '操作失败')
    }
  } catch (e) {
    console.error('保存失败:', e)
    ElMessage.error('操作失败')
  }
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取处理状态文本
const getProcessStatusText = (status) => {
  const statusMap = {
    1: '待处理',
    2: '已通过',
    3: '已打回',
    4: '已过期'
  }
  return statusMap[status] || '未知'
}

// 获取处理状态类型
const getProcessStatusType = (status) => {
  const typeMap = {
    1: 'warning',
    2: 'success',
    3: 'danger',
    4: 'info'
  }
  return typeMap[status] || ''
}

// 监听标签页切换
watch(activeTab, (newTab) => {
  if (newTab === 'processing') {
    loadProcessings()
  } else if (newTab === 'result') {
    loadResults()
  }
})

onMounted(() => {
  loadProcessings()
})
</script>

<style scoped>
.processing-manage {
  width: 100%;
  padding: 20px;
}

h1 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 28px;
}

.tab-header {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
}
</style>

